/**
 * Created by way on 16/9/17.
 */

const $ = require('../lib/kdom');
import cfg from '../config';
import * as ajax from '../lib/kajax';
import { formatDate } from '../util/formatDate';
import { get, post, getView } from '../util/api';
import { dateStr } from '../util/tool';
import * as pullFresh from '../lib/kpullFresh';
import { backPage, tabSwitch, message, closeMsg } from "../util/aid";

import Dialog from '../lib/kdialog';
const dialog = new Dialog();

let _view = require('raw-loader!./list.html'); // eslint-disable-line
// let _view = '';

let _userInfo = null;//参数
let _perm = null;//参数
let _params = null;//参数

let _url = {
  '10': "/ogs/join",
  '11': "/ogs/join",
  '12': "/ogs/deltail",
  '13': "/ogs/deltail",
  '14': "/ogs/join",
  '15': "/ogs/deltail",
  '16': "/ogs/deltail",
};//参数
let userStatus = {
  '10': '0',
  '11': '1',
  '12': '',
  '13': '',
  '14': '1',
  '15': '',
  '16': ''
};

// test
// let companyData =
//   {
//     "name": "诺亚大陆有限公司",
//     "logo": "http://www.nuoyadalu.com/img/nydlqr.jpg",
//     "url": "http://www.nuoyadalu.com/",
//     "address": "重庆市渝北区黄山大道中55号麒麟C座1203",
//     "email": "walteryu@163.com",
//     "explian": "14岁小女孩异想天开，参加2015年科技部“中国创新创业大赛”，广东省互联网行业团队第一，国家奖励100万，2016年5月22日深圳卫视“合伙中国人”融资节目，成功获得当当网李国庆、58同城姚劲波投资承诺"
//   };
let timer = null; //定时器
let listData = null; //listData
let site = null; // site 参数
// let perm = [['10', "专职坐席"], ['11', "对公专家成员"], ['12', "高级别领导"], ["13", "最高级别领导"], ['14', "网点线下服务"], ['15', "支行高级别管理人员"], ['16', "总行领导"]];
// let permArr = [10, 11, 12, 13, 14, 15, 16];
// let skill = [[10, "金融理财"], [11, "行用卡"], [12, "贷款"]];
// let 

export default class {
  path = '/ogs/list$';
  hash = '/ogs/list';
  title = '消息列表';

  constructor(opt) {
    opt = opt || {};
    this.path = opt.path || this.path;
    this.hash = opt.hash || this.hash;
    this.title = opt.title || this.title;
  }

  // 输出视图
  view(cb) {
    if (!_view) {
      // 静态资源浏览器有缓存,增加时标,强制刷新!
      getView(`${cfg.ogs.view.host}${cfg.ogs.view.list}?t=${(+new Date())}`, '', (rs) => {
        _view = rs;
        cb(null, _view);
      });
    } else
      cb(null, _view);
  }

  // 在已经加载的视图上操作
  bind(dv, params) {
    // site
    site = localStorage.getItem(cfg.app.nauoyaSite);
    site = site ? JSON.parse(site) : '';
    _params = params;
    _userInfo = _params.userInfo || {};
    _perm = _userInfo.perm[0];

    console.log(`我是列表`, params, _perm);
    console.log(`我是列表site`, site);

    // timerFun
    // timerFun(_perm);

    const refreshBox = $.qu('.pull-to-refresh-content');//下拉刷新页面的盒子
    let val = null;
    // 初始化下拉刷新页面
    pullFresh.start(refreshBox);

    // 添加'refresh'监听器
    $(refreshBox).on('refresh', (e) => {
      // 模拟1s的加载过程
      setTimeout(() => {
        dialog.loading();
        val = IS_HasClass($.qus('#listTabBox .tab-link'), 'data-val');

        getIssueList(val);
        // 停止
        // timerFun(_perm, timer);

        pullFresh.done('.pull-to-refresh-content');
      }, 1000);
    });

    dialog.loading();
    getIssueList();
    // tab 切换
    tabSwitch($.qus('#listTabBox .tab-link'), (that) => {
      dialog.loading();
      let val = that.getAttribute('data-val');
      console.log(val);
      if (!val) {
        getIssueList();
      } else
        createOrderList(listData, val);
    });
  }
}

// 获取列表
function getIssueList(val) {
  ajax.get(`${cfg.ogs.host}${cfg.ogs.getOrder}`, "", (rs) => {
    if (rs) {
      let r = JSON.parse(rs);
      listData = r;
      createOrderList(r, val);
    } else {
      alert('您好！获取消息列表失败！请退出重试！');
    }
  });
}

window.showOrderFun = (that, idx) => {
  let data = listData[idx];
  // console.log(_url[_perm]);
  $.router.go("/ogs/join", { issueId: data.issueId, issueInfo: data, userInfo: _userInfo, opts: _params.opts }, true);
  // $.router.go(_url[_perm], { issueId: data.issueId, issueInfo: data, userInfo: _userInfo, opts: _params.opts },true);
};

function createOrderList(data, filter) {
  console.log('加载工单', data, filter, _perm);

  if (!data && data.length <= 0) {
    $.id("orderList").innerHTML = "<h2 style='margin-top:1rem;text-align:center;'>暂无任何要处理的信息哦!</h2>"
  } else {
    let date = null;
    let rc = "";
    // let currPerm = userStatus[_perm];
    let currStatus = null;
    closeMsg('#orderList');
    for (let i = 0, o = data, len = o.length; i < len; i++) {
      currStatus = o[i].status;
      console.log('currStatus', currStatus);
      if (filter) { // 筛选
        console.log('filter', filter);
        if (_perm == '12' || _perm == '13') {
          if (filter == '1') {
            if (currStatus == '1' || currStatus == '0') {
              if (o[i].process > 1) {
                rc += piandaun(o[i], i);
              }
            }
          } else if (currStatus == filter) {
            if (o[i].process > 1) {
              rc += piandaun(o[i], i);
            }
          }
        } else if (_perm == '10') {
          if (filter == '1') {
            if (currStatus == '1' || currStatus == '0') {
              rc += piandaun(o[i], i);
            }
          } else if (currStatus == filter) {
            rc += piandaun(o[i], i);
          }
        }
      } else { // 未筛选
        if (_perm == '12' || _perm == '13') {
          if (currStatus == '1' || currStatus == '0')
            if (o[i].process > 1) rc += piandaun(o[i], i);
        } else if (_perm == '10') {
          rc += piandaun(o[i], i);
        }
      }
    }
    if (!rc) {
      message('#orderList');
    } else {
      $.html(orderList, rc)
    }
    dialog.close();
    // timerFun(_perm);
  };
}

function piandaun(data, i) {
  let date = null;
  let img = null;
  let name = null;
  let rc = '';
  date = formatDate('dd', data.createTime);
  if (date < formatDate('dd')) {
    date = formatDate('MM月dd', data.createTime);
  } else {
    date = formatDate('hh:mm', data.createTime);
  }
  try {
    img = JSON.parse(data.member[0])[0]
  } catch (error) { }
  rc += `<li class="olist" onclick="showOrderFun(this,'${i}')">
          <div class="item-content">
            <div class="item-media">
              <img src="${img || 'http://cas-10038118.cossh.myqcloud.com/ogs/img/to-head-img.jpg'}" style='width: 2.2rem;'>
            </div>
            <div class="item-inner">
              <div class="item-title-row">
                <div class="item-title">${data.title}</div>
                <div class="item-after" style="color: #b4b4b4;font-size: .5rem;">${date}</div>
              </div>
              <div class="item-subtitle" style="color: gray;font-size: .65rem;">${data.text}</div>
            </div>
          </div>
        </li>`;
  return rc;

}

function timerFun(_perm, val) {
  /*  if (_perm == 10)
     if (val) {
       clearInterval(val);
     } else {
       timer = setInterval(getIssueList, 100000);
     } */
}

function IS_HasClass(cls, key) {
  let rc = '';
  for (let i = 0; i < cls.length; i++) {
    if ($.hasClass(cls[i], 'active')) {
      rc = $.attr(cls[i], key);
    }
  }
  return rc;
}